﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Newtonsoft.Json;
using Baidu.Aip.Nlp;
using Newtonsoft.Json.Linq;

public partial class api_actions : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/plain";
        string result = "";
        string action = Request["action"].ToString().ToLower().Trim();

        switch (action)
        {
            case "index_data":
                result = index_data();
                break;
            case "site_data":
                result = site_data();
                break;
            case "get_banned_type":
                result = get_banned_type();
                break;
            case "get_check_article_number":
                result = get_check_article_number();
                break;
            case "check_words_zhuanyong":
                result = check_words_zhuanyong();
                break;
            case "check_words_tongyong":
                result = check_words_tongyong();
                break;
            case "new_words_type":
                result = new_words_type();
                break;
            case "clear_all_cache":
                result = clear_all_cache();
                break;
            case "getaccesstoken":
                result = getAccessToken();
                break;
            case "text_correct":
                result = text_correct();
                break;
                //case "checktext":
                //    result = checkText();
                //    break;
                //case "getchecknum":
                //    result = getCheckNum();
                //    break;
        }

        Response.Write(result);
    }
    private string text_correct()
    {
        //string result = "{\"log_id\": 7791259560389082051, \"item\": {\"vec_fragment\": [{\"ori_frag\": \"弟一\", \"begin_pos\": 14, \"correct_frag\": \"第一\", \"end_pos\": 18}, {\"ori_frag\": \"占在\", \"begin_pos\": 34, \"correct_frag\": \"站在\", \"end_pos\": 38}], \"score\": 0.301027, \"correct_query\": \"早晨当泰阳发出第一绿阳光的适候，我站在太山芝巅\"}, \"text\": \"早晨当泰阳发出弟一绿阳光的适候，我占在太山芝巅\"}";
        //return result;
        dynamic res = new ExpandoObject();
        try
        {
            string text = Request.Form["jcContent"];
            if (string.IsNullOrWhiteSpace(text))
            {
                res.error_code = -1;
                res.error_msg = "请输入待检测的文本！";
                return JsonConvert.SerializeObject(res);
            }
            Dictionary<string, object> para = BaiduAI.AppAuthParam();
            JObject jo = new Nlp(para["APIKey"].ToString(), para["SecretKey"].ToString()).Ecnet(text);
            
            ////text = text.Replace("\n", "").Replace("\r", "").Replace("\r\n", "");
            //string url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/ecnet";
            ////string url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer";
            //string accessToken = getAccessToken();
            ////url = url + "?charset=UTF-8&access_token=" + accessToken;
            //url = url + "?access_token=" + accessToken;

            //Dictionary<string, string[]> headers = new Dictionary<string, string[]>();
            //headers.Add("ContentType", new string[] { "", "application/json" });
            //string bodys = "{\"text\":\"" + text + "\"}";
            //string result = url.Post(bodys, headers, Encoding.GetEncoding("GBK"));
            return jo.ToString();
        }
        catch (Exception ex)
        {
            res.error_code = -2;
            res.error_msg = ex.Message;
            return JsonConvert.SerializeObject(res);
        }
    }
    private string getAccessToken()
    {
        return BaiduAI.getAccessToken();
    }
    private string clear_all_cache()
    {
        Cacheing.Clear(SettingHelper.cache_all);
        Cacheing.Clear(SettingHelper.cache_site);
        return "";
    }
    private string new_words_type()
    {
        string new_word_type = string.Format("keyword = {0}，type = {1}， desc = {2}, issure = {3}， repeatcount = {4} ", Request.Params["keyword"], Request.Params["type"], Request.Params["desc"], Request.Params["issure"], Request.Params["repeatcount"]);
        FileHelper.WriteTextFile(new_word_type);
        dynamic ret = new ExpandoObject();
        ret.errcode = "0";
        ret.errmsg = "";
        return JsonConvert.SerializeObject(ret);
    }
    private string check_words_tongyong()
    {
        dynamic ret = new ExpandoObject();
        string words = Request.Params["content"].Trim();
        if (words == "")
        {
            ret.errcode = -1;
            ret.errmsg = "请输入待检测违禁词的段落！";
            ret.data = "[]";
            return JsonConvert.SerializeObject(ret);
        }
        #region 暂时不用
        //if (System.Web.HttpContext.Current.Session["verifyCode"] == null)
        //{
        //    ret.errcode = -2;
        //    ret.errmsg = "验证码已失效！";
        //    ret.data = "[]";
        //    return JsonConvert.SerializeObject(ret);
        //}
        //string checkCode = Request.Params["hdCheckCode"].ToLower().Trim();
        //if (string.IsNullOrWhiteSpace(checkCode))
        //{
        //    ret.errcode = -3;
        //    ret.errmsg = "请输入验证码！";
        //    ret.data = "[]";
        //    return JsonConvert.SerializeObject(ret);
        //}
        //if (System.Web.HttpContext.Current.Session["verifyCode"].ToString().ToLower().Trim() != checkCode)
        //{
        //    ret.errcode = -4;
        //    ret.errmsg = "验证码不正确，请重新输入！";
        //    ret.data = "[]";
        //    return JsonConvert.SerializeObject(ret);
        //}
        #endregion

        System.Web.HttpContext.Current.Session["verifyCode"] = null;
        string host = "http://apis.5118.com";
        string path = "/bannedword";
        //string apikey = "89979CD501924022BA0BC50F0ADF4E16";

        string apikey = getBannedWordApiKey();

        string querys = "";
        string bodys = string.Format("txt={0}", words);
        string url = host + path;

        if (querys.Trim().Length > 0) url = url + "?" + querys.Trim();

        Dictionary<string, string[]> headers = new Dictionary<string, string[]>();
        headers.Add("Authorization", new string[] { "Set", apikey });
        headers.Add("ContentType", new string[] { "", "application/x-www-form-urlencoded; charset=UTF-8" });
        string result = url.Post(bodys, headers);
        return result;
    }
    private string getBannedWordApiKey()
    {
        string json = SettingHelper.ReadSiteSetting();
        Dictionary<string, object> dict = json.Json2Dictionary();
        dict = dict["site"].ToString().Json2Dictionary();
        dict = dict["thirdapp"].ToString().Json2Dictionary();
        Dictionary<string, object> web5118 = dict["web5118"].ToString().Json2Dictionary();
        return web5118["wjcjc"].ToString();
    }
    private string check_words_zhuanyong()
    {
        try
        {
            Dictionary<string, string[]> headers = new Dictionary<string, string[]>();
            headers.Add("UserAgent", new string[] { "", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36" });
            headers.Add("Accept", new string[] { "", "application/json, text/javascript, */*; q=0.01" });
            headers.Add("Accept-Encoding", new string[] { "Set", "gzip, deflate" });
            headers.Add("Referer", new string[] { "", "http://ci.lingke.pro/" });
            headers.Add("Accept-Language", new string[] { "Set", "zh-CN,zh;q=0.9" });
            headers.Add("X-Requested-With", new string[] { "Set", "XMLHttpRequest" });
            headers.Add("ContentType", new string[] { "", "application/x-www-form-urlencoded;charset=UTF-8" });

            string words_type = "";

            if (!string.IsNullOrWhiteSpace(Request.Form["words_type[]"]))
            {
                foreach (var s in Request.Form["words_type[]"].Split(new char[] { ',' })) words_type = words_type + "words_type[]=" + s + "&";
                words_type = words_type.TrimEnd(new char[] { '&' });
            }
            string data = words_type + "&check_text=" + Request.Form["check_text"];// "%E6%9E%AF%E5%B9%B2%E4%B8%83%2C%E4%B9%A0%E8%BF%91%E5%B9%B3%2C%E6%9D%8E%E5%85%8B%E5%BC%BA%2C%E5%B0%8F%E7%BA%A2%E4%B9%A6%E7%B1%8D%EF%BC%8C%E6%B7%98%E5%AE%9D";// Request.Form["check_text"];
            string url = "http://ci.lingke.pro/index/index/checkText";
            string result = url.Post(data, headers);
            return result;
        }
        catch(Exception ex)
        {
            return "";
        }
    }
    private string get_check_article_number()
    {
        try
        {
            string url = "http://ci.lingke.pro/index/index/getCheckNum";

            Dictionary<string, string[]> headers = new Dictionary<string, string[]>();
            headers.Add("UserAgent", new string[] { "", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36" });
            headers.Add("Accept", new string[] { "", "application/json, text/javascript, */*; q=0.01" });
            headers.Add("Accept-Encoding", new string[] { "Set", "gzip, deflate" });
            headers.Add("Referer", new string[] { "", "http://ci.lingke.pro/" });
            headers.Add("Accept-Language", new string[] { "Set", "zh-CN,zh;q=0.9" });
            headers.Add("X-Requested-With", new string[] { "Set", "XMLHttpRequest" });
            string result = url.Request("Get", headers);
            return result;
        }
        catch(Exception ex)
        {
            dynamic ret = new ExpandoObject();
            ret.code = -1;
            ret.msg = ex.Message;
            var data = Convert.ToString((new Random()).Next(10000,999999));
            ret.data = data;
            return JsonConvert.SerializeObject(ret);
        }
    }
    private string get_banned_type()
    {
        dynamic ret = new ExpandoObject();
        try
        {
            string json = SettingHelper.ReadSiteSetting();
            Dictionary<string, object> dict = json.Json2Dictionary();
            dict = dict["site"].ToString().Json2Dictionary();
            dict = dict["thirdapp"].ToString().Json2Dictionary();
            dict = dict["web5118"].ToString().Json2Dictionary();

            List<Dictionary<string, object>> banned = new List<Dictionary<string, object>>();
            if (Request["typeId"].ToString().ToLower() == "zy") banned = dict["bannedTypeZY"].ToString().Json2List();
            else banned = dict["bannedType"].ToString().Json2List();
            ret.errcode = 0;
            ret.errmsg = "";
            ret.data = banned;
            string res = JsonConvert.SerializeObject(ret);
            return res;
        }
        catch (Exception ex)
        {
            ret.code = -1;
            ret.msg = ex.Message;
            ret.data = "[]";
            return JsonConvert.SerializeObject(ret);
        }
    }
    private string site_data()
    {
        dynamic ret = new ExpandoObject();
        try
        {
            string json = SettingHelper.ReadSiteSetting();
            Dictionary<string, object> dict = json.Json2Dictionary();
            dict = dict["site"].ToString().Json2Dictionary();
            Dictionary<string, object> contactus = dict["contactus"].ToString().Json2Dictionary();
            List<Dictionary<string, object>> friendlink = dict["friendlink"].ToString().Json2List();
            ret.code = 0;
            ret.msg = "";
            dynamic data = new ExpandoObject();
            data.contactus = contactus;
            data.friendlink = friendlink;
            ret.data = data;
            return JsonConvert.SerializeObject(ret);
        }
        catch(Exception ex)
        {
            ret.code = -1;
            ret.msg = ex.Message;
            ret.data = "{}";
            return JsonConvert.SerializeObject(ret);
        }
    }
    private string index_data()
    {
        dynamic ret = new ExpandoObject();
        try
        {
            string json = SettingHelper.ReadSiteSetting();
            Dictionary<string, object> dict = json.Json2Dictionary();
            dict = dict["index"].ToString().Json2Dictionary();
            List<Dictionary<string, object>> dict_slides = dict["slides"].ToString().Json2List();
            IOrderedEnumerable<Dictionary<string, object>> slides = dict_slides.OrderBy(x => x["id"]);
            ret.code = 0;
            ret.msg = "";
            dynamic data = new ExpandoObject();
            data.slides = slides;

            List<Dictionary<string, object>> dict_biz = dict["biz"].ToString().Json2List();
            IOrderedEnumerable<Dictionary<string, object>> biz = dict_biz.OrderBy(x => x["id"]);
            data.services = biz;


            IOrderedEnumerable<Dictionary<string, object>> caseList = dict["case"].ToString().Json2List().OrderBy(x => x["id"]);
            List<Dictionary<string, object>> caseShow = new List<Dictionary<string, object>>();
            var data_case = caseList.Where(x => x["caseType"].ToString() == "caizhuang");
            Dictionary<string, object> caseData = new Dictionary<string, object>();
            caseData.Add("id", 1);
            caseData.Add("data", data_case);
            caseShow.Add(caseData);

            caseData = new Dictionary<string, object>();
            data_case = caseList.Where(x => x["caseType"].ToString() == "chongwu");
            caseData.Add("id", 2);
            caseData.Add("data", data_case);
            caseShow.Add(caseData);

            caseData = new Dictionary<string, object>();
            data_case = caseList.Where(x => x["caseType"].ToString() == "jianliduo");
            caseData.Add("id", 3);
            caseData.Add("data", data_case);
            caseShow.Add(caseData);

            caseData = new Dictionary<string, object>();
            data_case = caseList.Where(x => x["caseType"].ToString() == "lizi");
            caseData.Add("id", 4);
            caseData.Add("data", data_case);
            caseShow.Add(caseData);
            data.demo = caseShow;

            ret.data = data;
            string res = JsonConvert.SerializeObject(ret);
            return res;
        }
        catch(Exception ex)
        {
            ret.code = -1;
            ret.msg = ex.Message;
            ret.data = "[]";
            return JsonConvert.SerializeObject(ret);
        }
    }
}